import { RouteRecordRaw } from "vue-router";
import { constantRoutes } from "@/router";
import { store } from "@/store";
import MenuAPI from "@/api/menu";
import { RouteVO, MenuTreeList, IMeta } from "@/api/menu/model";

const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");

/**
 * Use meta.role to determine if the current user has permission
 *
 * @param roles 用户角色集合
 * @param route 路由
 * @returns
 */
const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  // if (route.meta && route.meta.roles) {
  //   // 角色【超级管理员】拥有所有权限，忽略校验
  //   if (roles.includes("ROOT")) {
  //     return true;
  //   }
  //   return roles.some((role) => {
  //     if (route.meta?.roles) {
  //       return route.meta.roles.includes(role);
  //     }
  //   });
  // }
  // return false;
  return true;
};

/**
 * 递归过滤有权限的动态路由
 *
 * @param routes 接口返回所有的动态路由
 * @param roles 用户角色集合
 * @returns 返回用户有权限的动态路由
 */
const filterAsyncRoutes = (routes: RouteVO[], roles: string[]) => {
  const asyncRoutes: RouteRecordRaw[] = [];
  routes.forEach((route) => {
    const tmpRoute = { ...route } as RouteRecordRaw; // 深拷贝 route 对象 避免污染
    if (hasPermission(roles, tmpRoute)) {
      // 如果是顶级目录，替换为 Layout 组件
      if (tmpRoute.component?.toString() == "Layout") {
        tmpRoute.component = Layout;
      } else {
        // 如果是子目录，动态加载组件
        const component = modules[`../../views/${tmpRoute.component}.vue`];
        if (component) {
          tmpRoute.component = component;
        } else {
          tmpRoute.component = modules[`../../views/error-page/404.vue`];
        }
      }

      if (tmpRoute.children && route.children && route.children.length > 0) {
        tmpRoute.children = filterAsyncRoutes(route.children, roles);
      } else {
        delete tmpRoute["children"];
      }

      asyncRoutes.push(tmpRoute);
    }
  });

  return asyncRoutes;
};

// menu To routes
const menuToRoutes = (menus: MenuTreeList[]): RouteVO[] => {
  const asyncRoutes: RouteVO[] = [];
  menus.forEach((menu) => {
    const tmpMenu = { ...menu } as MenuTreeList; // 深拷贝 menu 对象 避免污染
    const tmpRoute = { path: "", children: [] } as RouteVO; // 深拷贝 tmpMenu 对象 避免污染
    tmpRoute["path"] = tmpMenu.routePath;
    tmpRoute["name"] = tmpMenu.name;
    tmpRoute["component"] = tmpMenu.component;
    tmpRoute["redirect"] = tmpMenu.redirect;
    const meta: IMeta = {};
    meta["title"] = tmpMenu.title;
    meta["icon"] = tmpMenu.icon;
    meta["hidden"] = tmpMenu.status == "normal" ? true : false;
    meta["keepAlive"] = tmpMenu.keepAlive == 1 ? true : false;
    meta["alwaysShow"] = tmpMenu.alwaysShow == 1 ? true : false;
    tmpRoute["meta"] = meta;
    if (tmpMenu.childlist && menu.childlist) {
      tmpRoute.children = menuToRoutes(menu.childlist);
    }
    asyncRoutes.push(tmpRoute);
  });
  return asyncRoutes;
};
// setup
export const usePermissionStore = defineStore("permission", () => {
  // state
  const routes = ref<RouteRecordRaw[]>([]);

  // actions
  function setRoutes(newRoutes: RouteRecordRaw[]) {
    routes.value = constantRoutes.concat(newRoutes);
  }

  /**
   * 生成动态路由
   *
   * @param roles 用户角色集合
   * @returns
   */
  function generateRoutes(roles: string[]) {
    // return new Promise<RouteRecordRaw[]>((resolve, reject) => {
    //   const accessedRoutes = [
    //     {
    //       path: "/Teams",
    //       component: Layout,
    //       meta: {
    //         alwaysShow: false,
    //       },
    //       children: [
    //         {
    //           path: "index",
    //           component: () => import("@/views/teams/index.vue"),
    //           meta: {
    //             title: "Teams",
    //           },
    //         },
    //       ],
    //     },
    //   ];
    //   setRoutes([]);
    //   resolve(accessedRoutes);
    // });

    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      // 接口获取所有路由
      MenuAPI.getRoutes({})
        .then((data) => {
          console.log(
            "%c Line:138 🍇 menuToRoutes(data)",
            "color:#6ec1c2",
            menuToRoutes(data)
          );
          const routes = [
            // {
            //   path: "/system",
            //   component: "Layout",
            //   redirect: "/system/user",
            //   name: "/system",
            //   meta: {
            //     title: "系统管理",
            //     icon: "system",
            //     hidden: false,
            //   },
            //   children: [
            //     {
            //       path: "user",
            //       component: "system/user/index",
            //       name: "User",
            //       meta: {
            //         title: "用户管理",
            //         icon: "user",
            //         hidden: false,
            //         keepAlive: true,
            //       },
            //     },
            //     {
            //       path: "role",
            //       component: "system/role/index",
            //       name: "Role",
            //       meta: {
            //         title: "角色管理",
            //         icon: "role",
            //         hidden: false,
            //         keepAlive: true,
            //       },
            //     },
            //     {
            //       path: "menu",
            //       component: "system/menu/index",
            //       name: "Menu",
            //       meta: {
            //         title: "菜单管理",
            //         icon: "menu",
            //         hidden: false,
            //         keepAlive: true,
            //       },
            //     },
            //   ],
            // },
            // {
            //   path: "/Teams",
            //   component: "Layout",
            //   meta: {
            //     alwaysShow: false,
            //   },
            //   children: [
            //     {
            //       path: "index",
            //       component: "teams/index",
            //       meta: {
            //         title: "teams",
            //         icon: "team",
            //       },
            //     },
            //   ],
            // },
            ...menuToRoutes(data),
          ];
          // 过滤有权限的动态路由
          const accessedRoutes = filterAsyncRoutes(routes, roles);
          console.log(
            "%c Line:205 🥤 accessedRoutes",
            "color:#ffdd4d",
            accessedRoutes
          );
          console.log("%c Line:205 🌮 routes", "color:#f5ce50", routes);
          setRoutes(accessedRoutes);
          resolve(accessedRoutes);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 获取与激活的顶部菜单项相关的混合模式左侧菜单集合
   */
  const mixLeftMenus = ref<RouteRecordRaw[]>([]);
  function setMixLeftMenus(topMenuPath: string) {
    const matchedItem = routes.value.find((item) => item.path === topMenuPath);
    if (matchedItem && matchedItem.children) {
      mixLeftMenus.value = matchedItem.children;
    }
  }
  return {
    routes,
    setRoutes,
    generateRoutes,
    mixLeftMenus,
    setMixLeftMenus,
  };
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
